package com.cash.loan.common.annotation.support;

import com.alibaba.fastjson.JSONObject;
import com.cash.loan.common.annotation.UserLogin;
import com.cash.loan.common.entity.UserInfo;
import com.cash.loan.common.util.JedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author Administrator
 * @Date 2018-07-05 11:57
 */
public class UserLoginHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * 头部token标志
     */
    private static final String USER_LOGIN_TOKEN = "Access-Token";

    /**
     * 没传token的标志
     */
    private static final String NO_TOKEN = "no-token";

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(UserInfo.class) && parameter.hasParameterAnnotation(UserLogin.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer container,
                                  NativeWebRequest request,
                                  WebDataBinderFactory factory) throws Exception {

        //从请求头部得到token
        String token = request.getHeader(USER_LOGIN_TOKEN);
        if(StringUtils.isBlank(token)){
            return null;
        }

        if(NO_TOKEN.equals(token)) {
            return null;
        }

        //从redis中得到用户信息的json字符串
        String userInfo = JedisUtils.get(token);

        if(StringUtils.isBlank(userInfo)) {
            return null;
        }

        //反序列化
        JSONObject jsonObject = (JSONObject) JSONObject.parse(userInfo);
        UserInfo user = JSONObject.toJavaObject(jsonObject,UserInfo.class);

        return user;
    }
}
